<?php

class NewsController extends Controller {

    public $layout = 'main';
	public $currentTournament = null;
    
    public function accessRules() {
        return array(
            array('deny',
                'actions' => array('index'),
                'users' => array('?'),
            )
        );
    }

    public function filters() {
        return [ 'accessControl'];
    }

    public function actionIndex() {
    	/* Gets user's tournament and shows tournament by default. If there is no tournament
    	 * redirects to tournamentManegement to create or find tournaments */
    	if( !isset( Yii::app()->user->currentTournament ) ) $this->redirect( '/tournamentManagement' );
		$this->currentTournament = Tournaments::model()->findByPk( Yii::app()->user->currentTournament );
    	
        $this->render('index');
    }
    
    public function actionLoadNews( $idTournament, $page ){	
    	$tournaments = TournamentNews::loadNewsByTournamentPagination( $idTournament, $page );
		
		foreach( $tournaments as &$t ){
			if( $t['idUser'] === null ){ 
				$t['username'] = Yii::t( 'site', 'System' );
			}else{
				$t['username'] = Users::model()->findByPk( $t['idUser'] )->username;
			}
			
			$t['date'] = $this->formatDate( $t['date'] );
		}
		
		$this->renderJSON( $tournaments );
    }

    protected function formatDate( $dateString ){
    	$date = new \DateTime( $dateString );
    	$formatedDate = date_format( $date, 'd * Y H:i:s' );
    	$englishMonth = date_format( $date, 'F' );
    	return str_replace( '*', Yii::t( 'site', $englishMonth ), $formatedDate );
    }
}
